import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, TextInput, Image, ScrollView, FlatList
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import HTTP from '../../../../utils/http'
import { SearchInput } from '../../../../component/SearchInput.js';
import ToastUtil from '../../../../utils/toast'
const scale = GLOBAL.SCALE;
const searchLeft = require('../../../../imgs/customer/searchLeft.png');


export class LongListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;
		return {
			headerTitle: (params.orderType == 'P' ? '采购' : '销售') + '长约框架列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		let { pushIndex, orderType, periodType, isQhXhXsBiz } = props.navigation.state.params;
		this.data = {
			params: {
				orderType: orderType,
				periodType: periodType
			},
		}
		this.state = {
			newLotData: [],  // 待审批
			status: 'loading',
			loadIcon: false,  // 下拉涮新的 图标
			selectIndex: pushIndex
		}
		this.pageNo = 1;
		this.totalPage = 1;
		this.searchCode = '';
		this.isQhXhXsBiz = isQhXhXsBiz;
		this.onrefresh = false;   // 刷新  false    加载 true
	}

	componentWillMount () {
		this._getListData();
	}

	//获取待审批,已审批列表
	async _getListData () {
		let sendData = {
			searchCode: this.searchCode || null,
			onrefresh: this.onrefresh,  // 
			pageNo: this.pageNo,
			orderType: this.data.params.orderType,
			pageSize: '15',
			periodType: 'L',
			isQhXhXsBiz: this.isQhXhXsBiz,
			status: 'EXECUTING'   //  执行中
		}
		this.setState({
			loadIcon: true
		})
		let responseData = await HTTP.POST(API_GENERATE(API.LONG_ORDER_LIST), sendData);
		this.setState({
			loadIcon: false
		});
		if (responseData) {
			this.totalPage = responseData.totalPage;
			if (this.onrefresh) {  // 加载
				this.setState({
					newLotData: this.state.newLotData.concat(responseData.rows),
					status: 'data'
				})
			} else { // 刷新
				this.setState({
					newLotData: responseData.rows,
					status: responseData.rows.length ? 'data' : 'empty'
				})
			}
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	// 下拉更新函数
	_isLoadRefresh () {
		this.pageNo = 1;
		this.onrefresh = false;
		this._getListData();
	}

	//上拉加载
	_loadData () {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this.onrefresh = true;
			this._getListData();
		}
	}

	//跳审批页面
	_goDetail = (orderId, businessKey, taskId, formKey) => {
		this.props.navigation.navigate('ApprovaPage', {
			orderId, businessKey, taskId, formKey
		})
	}

	//数据加载出错回调
	_onErrorPress = () => {
		this.setState({
			status: 'loading'
		}, function () {
			this._getListData();
		})
	}

	//选中
	_selectFn = (index, itemData) => {
		let { isCreditExpired, isNotComplete, isFrozen } = itemData;
		if (isCreditExpired == '2') { //营业执照   0 正常，1 快过期，2 已过期   授信不受控制 加 !this.code
			ToastUtil.showWarning('企业营业执照已过期，无法交易')
			return
		}
		if (isNotComplete == '1') { // 信息不全   0 正常，1信息不全    授信不受控制 加 !this.code
			ToastUtil.showWarning('企业基础数据缺失，无法交易，请补充')
			return
		}
		if (isFrozen == 1) {
			ToastUtil.showWarning('冻结企业无法交易，若有疑问请联系风控部。')
			return
		}
		this.setState({
			selectIndex: index
		}, function () {
			let This = this;
			This.props.navigation.state.params.callBack(itemData, index);
			This.props.navigation.goBack();
		})
	}


	// 一条数据
	_renderItem (data) {
		let { companyName, orderId, orderItemList, orderType, bizStaffName, isFuture, isOrderMapping, longOrderId, deliveryExpireDays, isFrozen } = data.item;
		let { selectIndex } = this.state;
		let index = data.index;
		let buyImg = require('../../../../imgs/Group5.png');
		let sellImg = require('../../../../imgs/Group4.png');
		let lockImg = require('../../../../imgs/order/lock.png');
		let imageSource = orderType == 'P' ? require('../../../../imgs/apply/shopp.png') : require('../../../../imgs/apply/sellXin.png');
		return (
			<TouchableOpacity key={index} onPress={() => { this._selectFn(index, data.item) }}>
				<View style={styles.exBox}>
					{selectIndex == index ? (
						<Image source={require('../../../../imgs/apply/selectLong.png')} style={styles.imgPosition} />
					) : null}
					<View style={styles.exHead}>
						<View style={styles.exHeadLeft}>
							<Image style={styles.exHeadImg1} source={imageSource} />
							<Text numberOfLines={2} style={styles.exHeadTitle}>{companyName}</Text>
							{longOrderId ? <Text style={[styles.longText]}>长约执行</Text> : null}
							{isFuture && isFuture == '1' ? <Text style={styles.longTime}>远期</Text> : null}
							{isOrderMapping && isOrderMapping == 1 ? <Image style={styles.exHeadImg2} source={require('../../../../imgs/apply/con.png')} /> : null}
							{
								isFrozen ? <Image style={styles.isfrozen} source={lockImg} /> : null
							}
						</View>
						<Text style={styles.exHeadHref}>执行中</Text>
					</View>
					<View style={styles.exContent}>
						<View style={[styles.exComItem, styles.exComItemTe]}>
							<Text style={styles.exName}>订单号：</Text>
							<Text style={styles.exValue}>{orderId}</Text>
						</View>
						{
							orderItemList && orderItemList.map((item, index) => {
								return (
									<View style={[styles.exComItem, styles.exComItemTe]} key={index} >
										<View style={styles.exComItem}>
											<Text style={styles.exName}>商品名称：</Text>
											<Text style={[styles.exValue, { width: 110 * scale }]} numberOfLines={1} >{item.goodsName}</Text>
										</View>
										<View style={styles.exComItem}>
											<Text style={styles.exName}>商品数量：</Text>
											<Text style={styles.exValue}>{item.longOrderLimit || 0}</Text>
										</View>
									</View>)
							})
						}
						<View style={[styles.exComItem, styles.exComItemTe]}>
							<Text style={styles.exName}>申请人:</Text>
							<Text style={styles.exValue} >{bizStaffName}</Text>
						</View>
					</View>
				</View>
			</TouchableOpacity>
		)
	}

	//搜索value控制
	_setKeyWord = (txt) => {
		this.searchCode = txt.replace(/(^\s*)|(\s*$)/g, "");
		if (this.searchCode == '') {
			this.onrefresh = false;
			this.pageNo = 1;
			this._getListData();
		}
	}
	//点击搜索按钮
	_editing = () => {
		this.onrefresh = false;
		this.pageNo = 1;
		this._getListData();
	}

	render () {
		let { status } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.searchBox}>
					<SearchInput
						setKeyWord={(txt) => { this._setKeyWord(txt); }}
						inputLeftIcon={searchLeft}
						onSubmitEditing={() => { this._editing() }}
					/>
					<Text style={styles.searchText} onPress={() => { this._editing() }}>搜索</Text>
				</View>
				{
					status == 'data' ? (
						<View style={styles.listBox}>
							<FlatList
								data={this.state.newLotData}
								renderItem={(data) => this._renderItem(data)}
								refreshing={this.state.loadIcon}
								onRefresh={this._isLoadRefresh.bind(this)}
								onEndReachedThreshold={1}
								onEndReached={() => { this._loadData(); }}
							/>
						</View>
					) : null
				}
				<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this._onErrorPress} />
			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.light,
	},
	exBox: {
		backgroundColor: '#fff',
		marginTop: 12 * scale
	},
	exHead: {
		height: 44 * scale,
		marginLeft: 12 * scale,
		marginRight: 12 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.gray,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	exHeadLeft: {
		flexDirection: 'row',
		alignItems: 'center',
		flex: 1,
	},
	exHeadImg1: {
		width: 16 * scale,
		height: 16 * scale,
		marginRight: 5 * scale
	},
	exHeadTitle: {
		fontSize: 14 * scale,
		color: '#222',
		marginRight: 5 * scale,
		width: 250 * scale
	},
	longTime: {
		color: style.color.white,
		backgroundColor: '#49CAFF',
		fontSize: 11 * scale,
		height: 16 * scale,
		lineHeight: 16 * scale,
		borderRadius: 4 * scale,
		marginRight: 5 * scale,
		paddingLeft: 5 * scale,
		paddingRight: 5 * scale
	},
	exHeadImg2: {
		height: 12 * scale,
		width: 18 * scale,
	},
	exHeadHref: {
		fontSize: 13 * scale,
		color: style.color.extheme
	},
	exContent: {
		flexDirection: 'row',
		flexWrap: 'wrap',
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		paddingTop: 10 * scale
	},
	exComItem: {
		width: '50%',
		flexDirection: 'row',
		alignItems: 'center'
	},
	exComItemTe: {
		width: '100%'
	},
	exName: {
		fontSize: 12 * scale,
		color: style.color.inputPlaceholderColor,
		lineHeight: 26 * scale
	},
	exValue: {
		color: style.color.normal
	},
	listBox: {
		flex: 1,
	},
	imgPosition: { position: 'absolute', bottom: 0, right: 12 * scale }
	, longText: {
		marginTop: 2 * scale,
		marginLeft: 6 * scale,
		width: 50 * scale,
		height: 16 * scale,
		backgroundColor: '#FFB649',
		color: '#FFFFFF',
		fontSize: 11 * scale,
		textAlign: 'center',
		borderRadius: 4 * scale,
	},
	searchBox: {
		height: 50 * scale,
		paddingLeft: 5 * scale,
		paddingRight: 10 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		width: '100%',
		backgroundColor: '#fff'
	},
	searchText: {
		fontSize: 14 * scale,
		marginLeft: 5 * scale,
	},
	isfrozen: {
		marginRight: 5 * scale,
		width: 20 * scale,
		height: 20 * scale,
	}

})